Strings

Strings play a major role in a programming language. Apart from providing nicer user interactions, they can also serve as communication tool within the parts of the program. Python provides a rich set of tools for Pattern matching using RegExs, String formatting based on locate and Various encryption methods. We have seen basic String Formatting in previous chapter. In this chapter let’s study about some basic functions that operates on strings.

Creating Strings

  • Creating Empty String

    s = str()
    

    or

s = '' # quotes can be any of '' or ""
  • Creating String with Initial Value

    s = "Some text goes here"
    

Accessing the elements of Strings

String elements can be accessed using integer indices. A slice can also be specified for accessing a required part of the string

In [1]:
s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
s
Out[1]:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua'
In [2]:
s[10]
Out[2]:
'm'
In [3]:
s[20:] # start from 10 to end of string
Out[3]:
't amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua'
In [4]:
s[:20] # start from 0 to index 19
Out[4]:
'Lorem ipsum dolor si'
In [5]:
s[10:30:2] # start from 10, end at 29 with steps of 2
Out[5]:
'mdlrstae,c'
In [6]:
s[30:10:-2] # in reverse order
Out[6]:
'nc,eatsrld'

Operators on Strings

In [7]:
'Lorem' in s
Out[7]:
True
In [8]:
'Some Random text : ' + s
Out[8]:
'Some Random text : Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua'
In [10]:
for i,c in enumerate(s): # string is iterable
    if i == 11:
        break
    else:
        print(c,end='')
Lorem ipsum

Operations on Strings

If s is a string,

  • s.format(elements) formats s and returns it
  • s.join(elements) returns a string in which the elements have been joined by s separator.
  • s.capitalize() Return a copy of the string with its first character capitalized and the rest lowercased.
  • s.count(sub[, start[, end]]) Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
  • s.find(sub[, start[, end]]) Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
  • s.isalpha() Return True if all characters in the string are alphabetic and there is at least one character, False otherwise.
  • s.split(sep=None, maxsplit=-1) Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).
  • s.strip([chars]) Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped
In [17]:
s
Out[17]:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua'
In [18]:
s.count('it')
Out[18]:
2
In [19]:
s.find('it')
Out[19]:
19
In [20]:
s.split(',')
Out[20]:
['Lorem ipsum dolor sit amet',
 ' consectetur adipiscing elit',
 ' sed do eiusmod tempor incididunt ut labore et dolore magna aliqua']
In [21]:
part = s.split(',')[2]
part
Out[21]:
' sed do eiusmod tempor incididunt ut labore et dolore magna aliqua'
In [22]:
part = part.strip()
part
Out[22]:
'sed do eiusmod tempor incididunt ut labore et dolore magna aliqua'
In [23]:
part = part.upper()
part
Out[23]:
'SED DO EIUSMOD TEMPOR INCIDIDUNT UT LABORE ET DOLORE MAGNA ALIQUA'
In [24]:
'-'.join('defg')
Out[24]:
'd-e-f-g'
In [25]:
s = 'abcd'
In [26]:
s += 'defg'        # Appending
s
Out[26]:
'abcddefg'

This is just an overview of Python String Functions. There are many more functions which can do various tasks. You will get to know them when you need the functionality.